package com.example.chapter07_client;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter07_client.Constant.PermissionConstant;
import com.example.chapter07_client.Util.PermissionUtil;
import com.example.chapter07_client.Util.ToastUtil;

public class MonitorSmsActivity extends AppCompatActivity {
    private static final String TAG = "liu";

    private SmsGetObserver mObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitor_sms);
        //给指定Uri注册内容观察器，一但发生数据变化，就触发观察器的onChange方法
        //短信的Uri
        Uri uri = Uri.parse("content://sms");
        //Uri：是一个用于标识和定位资源的字符串，资源可以是文件、网络上的资源、媒体内容等
        /*registerContentObserver的第二个参数:
        * notifyForDescendents:
        * false：表示精确匹配，即只匹配该Uri,true:表示可以同时匹配其派生的Uri
        * 假如UriMatcher里注册的Uri共有以下类型：
        * 1、content://AUTHORITIES/table
        * 2、content://AUTHORITIES/table/#
          3、content://AUTHORITIES/table/subtable
          * 假如我们当前需要观察的Uri为content://AUTHORITIES/student：
          * 如果发生数据变化的Uri为3
          * 当notifyForDescendents为false,那么该ContentObserver会监听不到*/

        PermissionUtil.checkPermission(this, PermissionConstant.PERMISSION_SMS,
                PermissionConstant.REQUEST_SMS_CODE);

        mObserver = new SmsGetObserver(this);
        getContentResolver().registerContentObserver(uri, true, mObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getContentResolver().unregisterContentObserver(mObserver);
    }

    private static class SmsGetObserver extends ContentObserver {
        private final Context mContext;

        public SmsGetObserver(Context context) {
            super(new Handler(Looper.getMainLooper()));
            this.mContext = context;
        }

        @Override
        @SuppressLint({"Recycle", "Range"})
        public void onChange(boolean selfChange, @Nullable Uri uri) {
            super.onChange(selfChange, uri);
            /*onChange会多次调用，收到一条短信会调用两次onChange
             * mUri == content://sms/raw/20
             * mUri == content://sms/inbox/20
             * 安卓7.0以上系统，点击标记为已读，也会调用一次
             * mUri == content://sms
             * 收到一条短信都是uri后面都会有确定的一个数字，对应数据库的_id，比如20*/
            if (uri == null) {
                return;
            }
            if (uri.toString().contains("content://sms/raw") ||
                    uri.toString().contains("content://sms")) {
                return;
            }

            //通过内容解析器获取符合条件的结果集邮标
            Cursor cursor = mContext.getContentResolver().query(uri, new String[]{"address", "body", "date"}, null,
                    null, "date DESC");
            if(cursor == null){
                Log.d(TAG,"onChange method query failed: cursor is null");
                return;
            }
            if (cursor.moveToNext()) {
                //短信的发送号码
                String sender = cursor.getString(cursor.getColumnIndex("address"));
                //短信内容
                String content = cursor.getString(cursor.getColumnIndex("body"));
                Log.d(TAG, String.format("sender:%s,content:%s", sender, content));
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == PermissionConstant.REQUEST_SMS_CODE){
            boolean grant = PermissionUtil.checkGrant(grantResults);
            if(!grant){
                ToastUtil.show(this,"信息读取未授权");
                jumpToSettings();
            }
        }

    }

    private void jumpToSettings() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.fromParts("package",getPackageName(),null));
        startActivity(intent);
    }


}